var http = require('http');
var https = require('https');
var qs = require('querystring');
var fs = require("fs");

String.prototype.format = function(args) {
	var result = this;
	if (arguments.length > 0) {
		if (arguments.length == 1 && typeof (args) == "object") {
			for (var key in args) {
				if(args[key]!=undefined){
					var reg = new RegExp("({" + key + "})", "g");
					result = result.replace(reg, args[key]);
				}
			}
		}
		else {
			for (var i = 0; i < arguments.length; i++) {
				if (arguments[i] != undefined) {
					//var reg = new RegExp("({[" + i + "]})", "g");//这个在索引大于9时会有问题，谢谢何以笙箫的指出
					var reg = new RegExp("({)" + i + "(})", "g");
					result = result.replace(reg, arguments[i]);
				}
			}
		}
	}
	return result;
};

exports.post = function (host,port,path,data,callback) {
	
	var content = qs.stringify(data);  
	var options = {  
		hostname: host,  
		port: port,  
		path: path + '?' + content,  
		method:'GET'
	};  
	  
	var req = http.request(options, function (res) {  
		console.log('STATUS: ' + res.statusCode);  
		console.log('HEADERS: ' + JSON.stringify(res.headers));  
		res.setEncoding('utf8');  
		res.on('data', function (chunk) {  
			//console.log('BODY: ' + chunk);
			callback(chunk);
		});  
	});
	  
	req.on('error', function (e) {  
		console.log('problem with request: ' + e.message);  
	});  
	  
	req.end(); 
};

exports.get3 = function (url,data,callback,safe) {
	var content = qs.stringify(data);
	var url = url;
	var proto = http;
	if(safe){
		proto = https;
	}
	var req = proto.get(url, function (res) {  
		//console.log('STATUS: ' + res.statusCode);  
		console.log('HEADERS: ' + JSON.stringify(res.headers));  
		var size = 0;
    	var chunks = [];
		//res.setEncoding('utf8');  
		res.on('data', function (chunk) {  
			console.log('BODY: ' + chunk.length);
			console.log(chunk);
			size += chunk.length;
      		chunks.push(chunk);
		});  
		 res.on('end', function(){
		      //var data = Buffer.concat(chunks, size);
		      var data = new Buffer(size);  
		      for (var i = 0, pos = 0, l = chunks.length; i < l; i++) {  
		        var newbuf = chunks[i];  
		        newbuf.copy(data, pos);  
		        pos += newbuf.length;  
		      }  
		      callback(true,data);
		      console.log(data);
		      //console.log(data.toString())
		  });
	});
	  
	req.on('error', function (e) {  
		console.log('problem with request: ' + e.message);
		callback(false,e);
	});  
	  
	req.end(); 
};

exports.get2 = function (url,data,callback,safe) {
	var content = qs.stringify(data);
	var url = url + '?' + content;
	var proto = http;
	if(safe){
		proto = https;
	}
	console.info(url);
	var req = proto.get(url, function (res) {  
		//console.log('STATUS: ' + res.statusCode);  
		//console.log('HEADERS: ' + JSON.stringify(res.headers));  
		res.setEncoding('utf8');  
		res.on('data', function (chunk) {  
			console.log('BODY: ' + chunk);
			var json = JSON.parse(chunk);
			if(callback){
				callback(true,json);
			}
		});  
	});
	  
	req.on('error', function (e) {  
		console.log('problem with request: ' + e.message);
		if(callback){
			callback(false,e);
		}
	});  
	  
	req.end(); 
};

exports.get = function (host,port,path,data,callback,safe) {
	var content = qs.stringify(data);  
	var options = {  
		hostname: host,  
		path: path + '?' + content,  
		method:'GET'
	};
	if(port){
		options.port = port;
	}
	var proto = http;
	if(safe){
		proto = https;
	}
	var req = proto.request(options, function (res) {  
		//console.log('STATUS: ' + res.statusCode);  
		//console.log('HEADERS: ' + JSON.stringify(res.headers));  
		res.setEncoding('utf8');  
		res.on('data', function (chunk) {  
			//console.log('BODY: ' + chunk);
			var json = JSON.parse(chunk);
			callback(true,json);
		});  
	});
	  
	req.on('error', function (e) {  
		console.log('problem with request: ' + e.message);
		callback(false,e);
	});  
	  
	req.end(); 
};

exports.send = function(res,errcode,errmsg,data){
	if(data == null){
		data = {};
	}
	data.errcode = errcode;
	data.errmsg = errmsg;
	var jsonstr = JSON.stringify(data);
	res.send(jsonstr);
};


exports.downLoadShare=function(params,fileName,callback){

   var filePath = "./public/static/img/"+fileName;
   console.log("二维码图片获取 路径",filePath);
   fs.exists(filePath,function(exists){
		if(exists){
			console.log("获取二维码图片已经存在，返回");
			callback({"code":1,"errmsg":"success"});
			return;
		}else{
		console.log("获取二维码图片不存在，开始下载");
		var url = params.serverUrl;
		var agentId = params.agentId;
		//var qcodeUrl = "http://qr.liantu.com/api.php?logo="+url+"static/img/logo-agent.jpg&text="+url+"wxlogin?agent="+agentId;
		//var logo_url= url+"static/img/logo-agent.jpg";
		var logo_url="http://a4.qpic.cn/psb?/V121ZsBv4VAMRg/vWpvmzJaDB1HThOuzEFV4dMQdWNKrriiW3Q7Nu1JXss!/b/dPMAAAAAAAAA&ek=1&kp=1&pt=0&bo=SABIAEgASAADACU!&vuin=417137591&tm=1511920800&sce=60-1-1&rf=0-0";
		var text_url = encodeURIComponent(url+"wxlogin?agent="+agentId);
	//	logo-url = encodeURIComponent(logo-url);
		
		var qcodeUrl = "http://tool.kd128.com/qrcode?logo="+logo_url+"&text="+text_url;
	//	var qcodeUrl = "http://mobile.qq.com/qrcode?url="+url+"wxlogin?agent="+agentId;
		
		console.log("获取二维码url",qcodeUrl)
	
		http.get(qcodeUrl, function(res){
			var imgData = "";
			res.setEncoding("binary"); //一定要设置response的编码为binary否则会下载下来的图片打不开
			res.on("data", function(chunk){
				imgData+=chunk;
			});
			res.on("end", function(){

				if(imgData.length<10){
					callback({"code":-1,"errmsg":"api error"});	
					return
				}
				if(imgData.indexOf("Cannot GET")!=-1){
					callback({"code":-1,"errmsg":"api error"});	
					return
				}
				fs.writeFile(filePath, imgData, "binary", function(err){
					if(err){
						console.log(err);
						callback({"code":-1,"errmsg":err});
						//throw err;
					}else{
						console.log("down success");
						callback({"code":0,"errmsg":"success"});
					}
				});
			});
		});
		}
   });

};